package com.example.startactivity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import java.util.TreeSet;

public class MainActivity extends AppCompatActivity {
    private EditText editText;
    private EditText editText2;
    private SmallWindowView windowView;
    private WindowManager wm;
    private WindowManager.LayoutParams mLayoutParams;
    private final int OVERLAY_PERMISSION_REQ_CODE = 1;
    private TextView textView_name, tv_activityName;
    private Set<String> set = new TreeSet<>();
    private boolean isShow;
    private boolean isRun;

    private int setSize = 0;

    private Observer observer=new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            StringObservable stringObservable = (StringObservable) o;
            String s = stringObservable.getData();
            String[] s2 = s.split("/");
            textView_name.setText(s2[0] + "\n" + s2[1]);
            set.add(s);
            if (setSize != set.size()) {
                setSize = set.size();
                tv_activityName.append("\n" + s2[0] + "\n" + s2[1] + "\n");
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.ed_packge);
        editText2 = findViewById(R.id.ed_name);
        tv_activityName = findViewById(R.id.tv_activityName);
        initSmallViewLayout();

//        MyLiveData.getInstance().with("1",String.class).observeForever(new Observer<String>() {
//            @Override
//            public void onChanged(String s) {
//                String[] s2=s.split("/");
//
//                textView_name.setText(s2[0]+"\n"+s2[1]);
//                set.add(s);
//                if (setSize!=set.size()){
//                    setSize=set.size();
//                    tv_activityName.append(s2[0]+"\n"+s2[1]+"\n\n");
//                }
//            }
//        });

        WindowChangeDetectingService.stringObservable.addObserver(observer);
        try {
            setMyServiceEnable();
        }catch (Exception e){}
    }

    /**
     * 需要授予权限 android.permission.WRITE_SECURE_SETTINGS
     * adb shell pm grant 包名 android.permission.WRITE_SECURE_SETTINGS
     */
    private void setMyServiceEnable() {
        String name = getPackageName()+"/"+ WindowChangeDetectingService.class.getName();

        String string = Settings.Secure.getString(getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        StringBuffer stringBuffer=new StringBuffer(string);
        if (string==null){
            string="";
        }
        if (!string.contains(name)){
            String s = stringBuffer.append(":").append(name).toString();
            Settings.Secure.putString(getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,s);
        }
    }


    public void openActivity(View view) {
        String s = editText.getText().toString();
        String s1 = editText2.getText().toString();

        if (TextUtils.isEmpty(s) || TextUtils.isEmpty(s1)) {
            Toast.makeText(this, "请填写", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            Intent intent = new Intent();
            //com.ustcinfo.ict.ahhxapp 被启动包名；com.ustcinfo.ict.platform.ui.LoginActivity  被启动指定类全名
            intent.setClassName(s, s1);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "出错了", Toast.LENGTH_SHORT).show();
        }

    }


    public void initSmallViewLayout() {
        windowView = (SmallWindowView) LayoutInflater.from(this).inflate(R.layout.small_win, null);
        wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        textView_name = windowView.findViewById(R.id.tv_name);

//        mLayoutParams = new WindowManager.LayoutParams(
//                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
//                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
//                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
//                PixelFormat.TRANSLUCENT);
        mLayoutParams = new WindowManager.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
        mLayoutParams.gravity = Gravity.NO_GRAVITY;
        windowView.setWm(wm);
        windowView.setWmParams(mLayoutParams);

    }


    public void alertWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 7.0 以上需要引导用去设置开启窗口浮动权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0 以上type需要设置成这个
                mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            }
            requestDrawOverLays();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 6.0 动态申请
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}, 1);
        }
    }


    // android 23 以上先引导用户开启这个权限 该权限动态申请不了
    @TargetApi(Build.VERSION_CODES.M)
    public void requestDrawOverLays() {
        if (!Settings.canDrawOverlays(MainActivity.this)) {
            Toast.makeText(this, "can not DrawOverlays", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + MainActivity.this.getPackageName()));
            startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
        } else {
            if (wm != null && windowView.getWindowId() == null) {
                wm.addView(windowView, mLayoutParams);
            }
            Toast.makeText(this, "权限已经授予", Toast.LENGTH_SHORT).show();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (!Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "设置权限拒绝", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "设置权限成功", Toast.LENGTH_SHORT).show();
            }
        }
    }


    // 移除window
    public void dismissWindow() {
        if (wm != null && windowView != null && windowView.getWindowId() != null) {
            wm.removeView(windowView);
        }
    }


    public void showActivityName(View view) {
        if (!isShow) {

            isRun = true;
            isShow = true;
            alertWindow();

        } else {
            dismissWindow();
            isRun = false;
            isShow = false;
        }


    }


    //获取栈顶ActivityName
    public String getTopActivityName(Context context) {
        String topActivityClassName = null;
        ActivityManager activityManager =
                (ActivityManager) (context.getSystemService(android.content.Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
        if (runningTaskInfos != null) {
            ComponentName f = runningTaskInfos.get(0).topActivity;
            topActivityClassName = f.getClassName();
        }
        return topActivityClassName;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isShow = false;
        isRun = false;
        dismissWindow();
        WindowChangeDetectingService.stringObservable.deleteObservers();
    }

    public void startService(View view) {
        try {
            startActivity(new Intent("android.settings.ACCESSIBILITY_SETTINGS"));
        } catch (Exception e) {
            startActivity(new Intent("android.settings.SETTINGS"));
            e.printStackTrace();
        }
    }
}